package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.aop.LogOperation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //记录方法开始执行时间
        long start = System.currentTimeMillis();
        log.info("记录操作日志开始");
        //要保存的操作日志对象
        OperateLog operateLog = new OperateLog();
        //给log实体类赋值, 操作时间为当前系统时间
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());//Threadlocal，TokenFilter校验时，解析得登录用户id，存入ThreadLocal

        //获取类名
        String clsName = joinPoint.getTarget().getClass().getName();
        //System.out.println("clsName = " + clsName);
        operateLog.setClassName(clsName);
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //System.out.println("methodName = " + methodName);
        operateLog.setMethodName(methodName);
        //获取方法的参数
        Object[] args = joinPoint.getArgs();
        //System.out.println("args = " + Arrays.toString(args));
        operateLog.setMethodParams(Arrays.toString(args));

        Object result = null;
        try {
            //调用目标方法
            result = joinPoint.proceed();
            //记录方法执行的返回值
            operateLog.setReturnValue(result ==null?"":result.toString());
        } finally {
            // 记录方法执行耗时
            operateLog.setCostTime(System.currentTimeMillis() - start);
            // 保存到数据库表中
            operateLogMapper.insert(operateLog);
        }
        log.info("记录操作日志结束");
        return result;
    }

}
